package com.hfzy.ihk.web.userCenter.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.userCenter.entity.Priv;
import com.hfzy.ihk.facade.userCenter.entity.Role;
import com.hfzy.ihk.facade.userCenter.entity.UserHasRole;
import com.hfzy.ihk.facade.userCenter.entity.UserInfo;
import com.hfzy.ihk.facade.userCenter.vo.UserVo;
import com.hfzy.ihk.web.userCenter.mapper.PrivMapper;
import com.hfzy.ihk.web.userCenter.mapper.RoleMapper;
import com.hfzy.ihk.web.userCenter.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserApiController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PrivMapper privMapper;

    @RequestMapping("/findUserByUserName")
    public WebResult findUserByUserName(@RequestParam String userName){
        WebResult webResult = new WebResult();
        try{
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>();
            queryWrapper.eq("username", userName);
            UserInfo userInfo = userMapper.selectOne(queryWrapper);
            List<Role> roleList = roleMapper.getRoleByUserId(userInfo.getId());
            List<Priv> privs = privMapper.getPrivByUserId(userInfo.getId());
            String jsonStr = JSON.toJSONString(userInfo);
            UserVo userVo = JSON.parseObject(jsonStr,UserVo.class);
            userVo.setRoles(roleList);
            userVo.setPrivs(privs);
            List<UserVo> userVos = new ArrayList<>();
            userVos.add(userVo);
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setRecords(userVos);
            webResult.setMsg("成功");
        }catch (Exception e){
            webResult.setCode(GlobalStatic.CODE_N);
            webResult.setMsg("失败");
        }
        return webResult;
    }
}
